package cn.handwrit.springframework.support;

import cn.handwrit.springframework.BeansException;
import cn.handwrit.springframework.config.BeanDefinition;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{
//    @Override
//    protected Object createBean(String beanName, BeanDefinition beanDefinition) throws BeansException {
//        Object bean = null;
//        try {
//            bean = beanDefinition.getBeanClass().newInstance();
//        } catch (InstantiationException | IllegalAccessException e) {
//            throw new BeansException("Instantiation of bean failed", e);
//        }
//        //放入单例缓存
//        addSingleton(beanName,bean);
//        return bean;
//    }
    //注意这里可以选择那种创建实例化，这里选择的Cglib
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, beanName, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) throws BeansException {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                //注意这里创建参数，只对比了和构造参数长度是否一致，实际上spring还会对比每个参数的类型
                constructorToUse = ctor;
                break;
            }
        }
        return instantiationStrategy.instantiation(beanDefinition, beanName, constructorToUse, args);
    }

}
